<!--
 * @Author: weikang
 * @Description:
 * @Date: 2023-12-22 22:47:46
 * @LastEditTime: 2025-01-26 17:25:38
 * @FilePath: /env-manager-pc/src/views/contract/manager/index.vue
-->
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { isEmpty } from 'lodash-es'
import managerEdit from './manager.edit.vue'
import { useClassifys, useOwnerOrgs } from '@/utils/dataHook'
import { QueryObj } from '@/utils/dataHook/data'
import { usePage } from '@/utils/commonHook'
import type { doLoading } from '@/types/page'
import contractApi from '@/api/modules/contract'
import type { ContractRow } from '@/api/modules/types/contract'
import { ModelType } from '@/types/common'

const route = useRoute()
const loading = ref(false)

const searchData = reactive(new QueryObj({
  objType: 'DIM.FilterCollection',
  Filters: [
    { Type: 'DIM.GYHR.ContractFilters.TimeFilter',
      FilterKey: 'ContractStartTime',
      valueKey: 'ContractStartTime' },
    {
      Type: 'DIM.GYHR.ContractFilters.TimeFilter',
      FilterKey: 'ContractIncomeTime',
      valueKey: 'ContractIncomeTime',
    },
    {
      Type: 'DIM.GYHR.ContractFilters.TimeFilter',
      FilterKey: 'ContractInvoiceTime',
      valueKey: 'ContractInvoiceTime',
    },
    {
      Type: 'DIM.GYHR.ContractFilters.OwnerOrgClassify',
      FilterKey: '',
      valueKey: 'DIM.GYHR.ContractFilters.OwnerOrgClassify',
      mutlip: true,
    },
    {
      Type: 'DIM.GYHR.ContractFilters.OwnerOrgGUIDFilter',
      FilterKey: '',
      valueKey: 'DIM.GYHR.ContractFilters.OwnerOrgGUIDFilter',
      mutlip: true,
    },
    {
      Type: 'DIM.GYHR.ContractFilters.CodeFilter',
      FilterKey: '',
      valueKey: 'DIM.GYHR.ContractFilters.CodeFilter',
      mutlip: true,
    },
  ],
}))
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)

if (!isEmpty(route.query)) {
  Object.keys(route.query).forEach((key) => {
    searchData[key] = route.query[key]
  })
  search()
}

const OwnerList = useOwnerOrgs()
const OwnerOrgClassify = useClassifys()
const defaultProps = {
  children: 'Children',
  label: 'Name',
}
const editRef = ref()

function search() {
  page.PageNum = 1
  getTableData()
}
const tableData = ref<ContractRow[]>([])

async function getTableData() {
  loading.value = true
  const res = await contractApi.GetContracts({
    objFilter: searchData.getQuery(),
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  // console.log('%c [ res ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  const { Objs, RecordsetCount } = res
  tableData.value = Objs || []
  page.RecordsetCount = RecordsetCount
}

function toCreate() {
  editRef.value.open({ type: ModelType.add })
}
function toEdit(row: ContractRow) {
  editRef.value.open({ type: ModelType.edit, data: row })
}

getTableData()

async function submitEdit(formData: ContractRow, doLoading: doLoading) {
  try {
    doLoading(true)
    const isCreate = !formData.ObjID
    const res = isCreate
      ? await contractApi.ContractsAdd({
        contract: formData,
      })
      : await contractApi.ContractsUpdate({
        contractObjID: formData.ObjID,
        contract: formData,
      })
    editRef.value.upload(res.ObjID)
    getTableData()
    editRef.value.close()
    ElMessage.success({
      message: isCreate ? '新增成功' : '编辑成功',
      type: 'success',
    })
  }
  catch (e) {
    doLoading(false)
  }
}

async function toDel(row: ContractRow) {
  await ElMessageBox.confirm(`确定删除合同 ${row.ContractCode} 吗？`, '提示', {
    type: 'warning',
  })
  await contractApi.ContractsDelete({ contractObjID: row.ObjID })
  ElMessage.success({
    message: '删除成功',
    type: 'success',
  })
  getTableData()
}
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol :span="6">
              <ElFormItem label="合同编号">
                <ElInput v-model="searchData['DIM.GYHR.ContractFilters.CodeFilter']" clearable />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="合同类型">
                <ElSelect v-model="searchData['DIM.GYHR.ContractFilters.OwnerOrgClassify']" class="w-full" clearable>
                  <ElOption v-for="(label, value) in OwnerOrgClassify" :key="value" :value="value" :label="label" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="合同生效日期">
                <ElDatePicker v-model="searchData.ContractStartTime" value-format="YYYYMMDD" type="daterange" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="运维公司">
                <el-tree-select
                  v-model="searchData['DIM.GYHR.ContractFilters.OwnerOrgGUIDFilter']"
                  value-key="Code"
                  class="w-full"
                  :data="OwnerList"

                  :render-after-expand="false"
                  :props="defaultProps"
                  clearable check-strictly
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="收款日期">
                <ElDatePicker v-model="searchData.ContractIncomeTime" value-format="YYYYMMDD" type="daterange" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="开票日期">
                <ElDatePicker v-model="searchData.ContractInvoiceTime" value-format="YYYYMMDD" type="daterange" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="6" class="flex flex-justify-end">
              <ElButton type="primary" @click="search">
                查询
              </ElButton>
              <ElButton type="success" @click="toCreate">
                新增
              </ElButton>
              <ElButton type="warning">
                导出
              </ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-table
          border
          height="100%"
          :data="tableData"
          :loading="loading"
          :row-config="{ isCurrent: true }"
        >
          <VxeColumn title="序号" type="seq" width="80" />
          <VxeColumn field="date" title="合同类型" min-width="100" />
          <VxeColumn field="OwnerOrgName" title="合同所属公司" min-width="130" />
          <VxeColumn field="ContractCode" title="合同编号" min-width="160" show-overflow />
          <VxeColumn field="StartTime" title="合同生效时间 " min-width="180" />
          <VxeColumn field="EndTime" title="合同结束时间" min-width="180" />
          <VxeColumn field="TotalMoney" title="合同金额（元）" min-width="120" />
          <VxeColumn field="IncomeMoney" title="实收金额（元）" min-width="120" />
          <VxeColumn field="IncomeTime" title="收款日期" width="180" />
          <VxeColumn field="InvoiceMoney" title="开票金额（元）" width="120" />
          <VxeColumn field="InvoiceTime" title="开票时间" width="180" />
          <VxeColumn fixed="right" title="操作" width="150">
            <template #default="{ row }">
              <ElButton type="primary" link @click="toEdit(row)">
                修改
              </ElButton>
              <ElButton type="danger" link @click="toDel(row)">
                删除
              </ElButton>
            </template>
          </VxeColumn>
        </vxe-table>
      </div>
      <ElPagination
        class="mt-4"
        :page-size="page.PageSize"
        :total="page.RecordsetCount"
        :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50, 100]"
        @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
    </PageMain>
    <managerEdit ref="editRef" @submit="submitEdit" @refresh-list="getTableData" />
  </div>
</template>
